'use strict';

const Service = require('egg').Service;
const { wxpayConfig } = require('../../config/cert/wxpay.config');

class VipOrderService extends Service {

    async jsapi(order, openid) {
        return await this.service.wechatPay.jsapi(order, openid, '开通VIP', wxpayConfig.vipNotifyUrl);
    }

    async query(out_trade_no) {
        //查询订单
        const order = await this.service.wechatPay.orderqueryByOutTradeNo(out_trade_no);
        //处理业务逻辑
        this.updateOrder(order.out_trade_no, order.transaction_id);
    }

    async findByOrderNo(order_no) {
        return await this.ctx.model.OrderVip.findOne({
            where: {
                order_no
            }
        })
    }

    async updateOrder(order_no, transaction_id) {
        const order = await this.findByOrderNo(order_no);
        if (order && order.status == 1) {
            let user = await this.ctx.model.User.findByPk(order.user_id);
            if (!user) {
                this.ctx.helper.commonErr("用户不存在");
            }
            const transaction = await this.ctx.model.transaction();
            try {
                //更新订单
                order.status = 2;
                order.transaction_id = transaction_id;
                order.save();
                //更新用户信息
                user = await this.service.user.getVipTime(user, order.count * 30.5);
                user.get_like += 1;
                user.use_like += 1;
                user.save()

                await transaction.commit();
            } catch(e) {
                console.log(e);
                await transaction.rollback();
            }
        }
    }

}

module.exports = VipOrderService;